package chapter19;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/24 22:22
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        final int num = 3;
        final CyclicBarrier barrier = new CyclicBarrier(num, () -> {
            System.out.println("all persons have arrived");
            System.out.println("this is executed by " + Thread.currentThread().getName());
        });
        for (int i = 0; i < num; i++) {
            new Thread(new Tourist(barrier)).start();
        }
    }

    static class Tourist implements Runnable {
        private CyclicBarrier barrier;

        public Tourist(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                //集合点A
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " arrive at point A");

                TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                //集合点B
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " arrive at point B");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
